package Sort;

import java.util.Arrays;
//插入排序:
// 时间复杂度：O(N)/O(N^2) 

//稳定的排序，时间复杂度
//从小 到 大
public class InsertSort {

    public void sort1(int[] array) {
        for (int i = 1; i < array.length; i++) {
            for (int j = i - 1; j >= 0; j--) {
                if (array[j] > array[j + 1]) {
                    //交换
                    int tmp = array[j+1];
                    array[j + 1] = array[j];
                    array[j] = tmp;
                }else {
                    break;
                }
            }
        }
    }
    //插入排序2，更高效
    public static void sort11(int[] array){
        for (int i = 1; i < array.length ; i++) {
            int tmp = array[i];
            int j = i-1;
            for (;j >=0 ; j--) {
                if(array[j]>tmp){
                    array[j+1] = array[j];
                }else {
                    break;
                }
            }
            array[j+1] = tmp;
        }
    }

    //区间的插入排序
    public static void sortRange(int[] array,int begin,int end){
        for (int i = begin+1; i <= end; i++) {
            int tmp = array[i];
            int j = i-1;
            for (;j >=begin ; j--) {
                if(array[j]>tmp){
                    array[j+1] = array[j];
                }else {
                    break;
                }
            }
            array[j+1] = tmp;
        }
    }

    public static void  TestSort(int[] array){
        int[] tmp = Arrays.copyOf(array,array.length);
        long time1 = System.currentTimeMillis();
        sort11(tmp);
        long time2 = System.currentTimeMillis();
        System.out.println("排序用时："+(time2-time1));

    }

    //创建最坏情况的排序
    public static void createArray(int[] array){
        for (int i = 0; i < array.length ; i++) {
            array[i] = array.length-i;
        }
    }

    public static void main(String[] args) {
        int[] array = new int[10_0000];
        //完全逆序
        createArray(array);
        TestSort(array);
    }
}
